package com.asurplus.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.asurplus.common.layui.LayuiTreePojo;
import com.asurplus.common.shiro.ShiroUtils;
import com.asurplus.common.utils.ResponseResult;
import com.asurplus.system.entity.SysDeptInfo;
import com.asurplus.system.mapper.SysDeptInfoMapper;
import com.asurplus.system.service.SysDeptInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lizhou
 * @since 2020-11-24
 */
@Service
public class SysDeptInfoServiceImpl extends ServiceImpl<SysDeptInfoMapper, SysDeptInfo> implements SysDeptInfoService {

    @Override
    public List<SysDeptInfo> list() {
        LambdaQueryWrapper<SysDeptInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(SysDeptInfo::getPid).orderByAsc(SysDeptInfo::getSort);
        return this.list(queryWrapper);
    }

    @Override
    public ResponseResult add(SysDeptInfo sysDeptInfo) {
        if (null == sysDeptInfo) {
            return ResponseResult.error("数据错误");
        }
        if (StringUtils.isBlank(sysDeptInfo.getName())) {
            return ResponseResult.error("请输入部门名称");
        }
        LambdaQueryWrapper<SysDeptInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDeptInfo::getPid, sysDeptInfo.getPid());
        queryWrapper.eq(SysDeptInfo::getName, sysDeptInfo.getName());
        SysDeptInfo dbObj = this.getOne(queryWrapper, false);
        if (null != dbObj) {
            return ResponseResult.error("该部门已经存在，请勿重复添加");
        }
        sysDeptInfo.setCreateUser(ShiroUtils.getSysUserId());
        this.baseMapper.insert(sysDeptInfo);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult update(SysDeptInfo sysDeptInfo) {
        if (null == sysDeptInfo || null == sysDeptInfo.getId() || 0 == sysDeptInfo.getId()) {
            return ResponseResult.error("数据错误");
        }
        if (StringUtils.isBlank(sysDeptInfo.getName())) {
            return ResponseResult.error("请输入部门名称");
        }
        LambdaQueryWrapper<SysDeptInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDeptInfo::getPid, sysDeptInfo.getPid());
        queryWrapper.eq(SysDeptInfo::getName, sysDeptInfo.getName());
        queryWrapper.ne(SysDeptInfo::getId, sysDeptInfo.getId());
        SysDeptInfo dbObj = this.getOne(queryWrapper, false);
        if (null != dbObj) {
            return ResponseResult.error("该部门已经存在，请勿重复添加");
        }
        sysDeptInfo.setUpdateUser(ShiroUtils.getSysUserId());
        this.baseMapper.updateById(sysDeptInfo);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult del(Integer id) {
        SysDeptInfo sysDeptInfo = this.baseMapper.selectById(id);
        if (null == sysDeptInfo) {
            return ResponseResult.error("数据错误");
        }
        // 所有下级ids
        StringBuffer ids = new StringBuffer();
        ids.append(id).append(",");
        // 删除下级
        StringBuffer pidBuffer = new StringBuffer();
        pidBuffer.append(id);
        boolean flag = true;
        while (flag) {
            // 查询下级ids
            String childerIds = this.baseMapper.getChilderIds(pidBuffer.toString());
            if (StringUtils.isNotBlank(childerIds)) {
                pidBuffer = new StringBuffer();
                pidBuffer.append(childerIds);
                // 下级ids
                ids.append(childerIds).append(",");
            } else {
                flag = false;
            }
        }
        // 删除自身和下级
        ids.deleteCharAt(ids.length() - 1);
        this.baseMapper.deleteBatch(ids.toString());
        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Integer status) {
        SysDeptInfo sysDeptInfo = this.baseMapper.selectById(id);
        if (null == sysDeptInfo) {
            return ResponseResult.error("数据错误");
        }
        // 所有下级ids
        StringBuffer ids = new StringBuffer();
        ids.append(id).append(",");
        // 删除下级
        StringBuffer pidBuffer = new StringBuffer();
        pidBuffer.append(id);
        boolean flag = true;
        while (flag) {
            // 查询下级ids
            String childerIds = this.baseMapper.getChilderIds(pidBuffer.toString());
            if (StringUtils.isNotBlank(childerIds)) {
                pidBuffer = new StringBuffer();
                pidBuffer.append(childerIds);
                // 下级ids
                ids.append(childerIds).append(",");
            } else {
                flag = false;
            }
        }
        // 修改自身和下级
        ids.deleteCharAt(ids.length() - 1);
        this.baseMapper.updateStatusBatch(ids.toString(), status);
        return ResponseResult.success();
    }

    @Override
    public String listDeptInfoTree(Integer deptId) {
        List<LayuiTreePojo> resList = new ArrayList<>();
        List<LayuiTreePojo> list = this.baseMapper.listDeptInfoTree();
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        // 迭代
        Iterator<LayuiTreePojo> iterator = list.iterator();
        LayuiTreePojo layuiTreePojo = null;
        // 找出第一级
        while (iterator.hasNext()) {
            layuiTreePojo = iterator.next();
            if (0 == layuiTreePojo.getPid()) {
                resList.add(layuiTreePojo);
                iterator.remove();
            }
        }
        // 如果一级部门为空，直接返回
        if (CollectionUtil.isEmpty(resList)) {
            return JSONObject.toJSONString(resList);
        }
        // 找出第二级
        List<LayuiTreePojo> list1 = null;
        for (LayuiTreePojo item : resList) {
            iterator = list.iterator();
            while (iterator.hasNext()) {
                layuiTreePojo = iterator.next();
                if (item.getId().equals(layuiTreePojo.getPid())) {
                    list1 = item.getChildren();
                    if (CollectionUtil.isEmpty(list1)) {
                        list1 = new ArrayList<>();
                    }
                    list1.add(layuiTreePojo);
                    item.setChildren(list1);
                    iterator.remove();
                }
            }
        }
        return JSONObject.toJSONString(resList);
    }

    @Override
    public ResponseResult updateSort(Integer id, Integer sort) {
        if (null == id || 0 == id || null == sort) {
            return ResponseResult.error("数据错误");
        }
        SysDeptInfo sysDeptInfo = this.baseMapper.selectById(id);
        if (null == sysDeptInfo) {
            return ResponseResult.error("数据错误");
        }
        if (sort.equals(sysDeptInfo.getSort())) {
            return ResponseResult.success();
        }
        sysDeptInfo.setSort(sort);
        this.baseMapper.updateById(sysDeptInfo);
        return ResponseResult.success();
    }
}
